package com.gitee.swsk33.nuistcanteenselector.service.impl;

import com.gitee.swsk33.nuistcanteenselector.dao.CanteenDAO;
import com.gitee.swsk33.nuistcanteenselector.dataobject.Canteen;
import com.gitee.swsk33.nuistcanteenselector.model.Result;
import com.gitee.swsk33.nuistcanteenselector.service.CanteenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class CanteenServiceImpl implements CanteenService {

	@Autowired
	private CanteenDAO canteenDAO;

	@Override
	public Result<Set<Canteen>> getByType(String type) {
		List<Canteen> canteens = null;
		Result<Set<Canteen>> result = new Result<>();
		try {
			canteens = canteenDAO.getByType(type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (canteens == null || canteens.size() == 0) {
			result.setResultFailed("找不到符合条件的餐厅！");
			return result;
		}
		Set<Canteen> canteenSet = new HashSet<>();
		canteenSet.addAll(canteens);
		result.setResultSuccess("获取餐厅列表成功！", canteenSet);
		return result;
	}

	@Override
	public Result<Set<Canteen>> getByTypeAndPrice(String type, Integer min, Integer max) {
		List<Canteen> canteens = null;
		Result<Set<Canteen>> result = new Result<>();
		try {
			canteens = canteenDAO.getByType(type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (canteens == null || canteens.size() == 0) {
			result.setResultFailed("找不到符合条件的餐厅！");
			return result;
		}
		Set<Canteen> canteenSet = new HashSet<>();
		for (Canteen canteen : canteens) {
			if (canteen.getAveragePrice() >= min && canteen.getAveragePrice() <= max) {
				canteenSet.add(canteen);
			}
		}
		if (canteenSet.size() == 0) {
			result.setResultFailed("找不到符合条件的餐厅！");
			return result;
		}
		result.setResultSuccess("获取餐厅列表成功！", canteenSet);
		return result;
	}

	@Override
	public Result<List<Canteen>> getAll() {
		List<Canteen> canteens = null;
		Result<List<Canteen>> result = new Result<>();
		try {
			canteens = canteenDAO.getAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (canteens == null || canteens.size() == 0) {
			result.setResultFailed("获取餐厅列表失败！");
			return result;
		}
		result.setResultSuccess("获取餐厅列表成功！", canteens);
		return result;
	}

}